package hu.ibm.web.user;

import hu.ibm.service.AuthenticationService;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.apache.log4j.Logger;

@ManagedBean(name = "springLoginBean")
@SessionScoped
public class SpringLoginBean implements Serializable {
	   private static Logger logger = Logger.getLogger(SpringLoginBean.class);
	private static final long serialVersionUID = 1L;
	@Size(min = 2, max = 30)
	@Pattern(regexp = "[\\s\\w-,!\\.]*", message = "must match a-z,A-Z,0-9 or !,-_.")
	private String username;
	@Size(min = 2, max = 20)
	@Pattern(regexp = "[\\s\\w-,!\\.]*", message = "must match a-z,A-Z,0-9 or !,-_.")
	private String password;
	private String message;
	private Boolean rememberMe;

	@ManagedProperty(value = "#{authenticationService}")
	private AuthenticationService authenticationService;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(final String password) {
		this.password = password;
	}

	public String cancel() throws ValidatorException {
		String msgText = "Wrong username or password";
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
				msgText, null);
		throw new ValidatorException(msg);

	}

	public void setRememberMe(Boolean rememberMe) {
		this.rememberMe = rememberMe;
	}

	public Boolean getRememberMe() {
		return rememberMe;
	}

	public String login() {

		boolean success = authenticationService.login(username, password);
		logger.info("login() " + success );
		
		if (success) {
			return "/index.xhtml"; 
		} else {
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage("Login or password incorrect."));
			return "login";
		}
	}

	public void setAuthenticationService(
			AuthenticationService authenticationService) {
		this.authenticationService = authenticationService;
	}

}